﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClumsyWordsPortableLibrary.Shared;
using Windows.Storage;
using System.IO;
using Newtonsoft.Json;

namespace ClumsyWordsW8
{
    public class FileStorageHelper<T> : IFileStorage<T>
    {
        private StorageFolder localFolder = ApplicationData.Current.LocalFolder;

        public string ReadData(String targetFileName) 
        {
            return this.LoadAsync(targetFileName).ToString();
        }

        public void Delete(String targetFileName)
        {
            this.DeleteFileAsync(targetFileName).Wait();
        }

        public void SaveDataToIsolatedStorage(T sourceData, String targetFileName)
        {
            this.SaveAsync(sourceData, targetFileName).Wait();
        }

        public async Task SaveAsync(T sourceData, String targetFileName)
        {

            StorageFile file = await localFolder.CreateFileAsync(targetFileName, CreationCollisionOption.ReplaceExisting);

            Stream writeStream = await file.OpenStreamForWriteAsync();

            using (StreamWriter writer = new StreamWriter(writeStream))
            {
                string data = await JsonConvert.SerializeObjectAsync(sourceData);

                await writer.WriteAsync(data);
                await writer.FlushAsync();
            }
        }

        public async Task<T> LoadAsync(String fileName)
        {
            StorageFile file = null;
            bool exists = true;
            try
            {
                file = await localFolder.GetFileAsync(fileName);
            }
            catch (FileNotFoundException)
            {
                exists = false;
            }
            if (!exists)
            {
                await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.FailIfExists);
                return default(T);
            }

            Stream inStream = await file.OpenStreamForReadAsync();

            using (StreamReader reader = new StreamReader(inStream))
            {
                string data = await reader.ReadToEndAsync();
                reader.Dispose();
                T model = await JsonConvert.DeserializeObjectAsync<T>(data);
                return model;
            }
        }

        public async Task DeleteFileAsync(String targetFileName)
        {
            StorageFile file = null;
            bool exists = true;
            try
            {
                file = await localFolder.GetFileAsync(targetFileName);
            }
            catch (FileNotFoundException)
            {
                exists = false;
            }
            if (exists)
            {
                await file.DeleteAsync();
            }
        }


    }
}
